package com.kla.power.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kla.power.entity.MenuEntity;
import com.kla.power.mapper.MenuMapper;
import com.kla.power.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kla.power.util.ConstUtil;
import com.kla.power.util.StateEnum;
import com.kla.power.util.StateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author WuZH
 * @since 2024-06-02
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> implements IMenuService {


    @Resource
    private MenuMapper menuMapper;

    /**
     * @param menuEntity
     * @return
     */
    @Override
    public List<MenuEntity> queryList (MenuEntity menuEntity) {
        //1. 查询一级封装为key
        List<MenuEntity> menuEntities = menuMapper.queryList ( menuEntity );
        //2. 查询每个一级的所有二级
        for ( MenuEntity menu : menuEntities ) {
            List<MenuEntity> childEntities = baseMapper.selectList ( new QueryWrapper<MenuEntity> ().eq ( "type", ConstUtil.MENU_TYPE_CHILD ).eq ( "parentId", menu.getId () ).orderByAsc ( "sort" ) );
            menu.setMenuEntities ( childEntities );
        }
        return menuEntities;
    }


    /**
     * 登录时获取左侧菜单，获取父子树形结构
     * @param menuEntity
     * @return
     */
    @Override
    public List<MenuEntity> queryMenus (MenuEntity menuEntity) {
        if ( menuEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        QueryWrapper<MenuEntity> queryWrapper = new QueryWrapper<> ();
        if ( menuEntity.getType () != null ) {
            queryWrapper.eq ( "type", menuEntity.getType () );
        }
        if ( StringUtils.isNotBlank ( menuEntity.getParentId () ) ) {
            queryWrapper.eq ( "parentId", menuEntity.getParentId () );
        }
        if ( StringUtils.isNotBlank ( menuEntity.getRoleId () ) ) {
            queryWrapper.eq ( "roleId", menuEntity.getRoleId () );
        }
        List<MenuEntity> menuEntities = menuMapper.queryList(menuEntity);
        for ( MenuEntity menu : menuEntities ) {
            MenuEntity child = new MenuEntity ();
            child.setParentId ( menu.getId () );
            child.setType ( ConstUtil.MENU_TYPE_CHILD );
            child.setRoleId ( menuEntity.getRoleId () );
            List<MenuEntity> childMenus = menuMapper.queryList ( child );
            menu.setMenuEntities ( childMenus );
        }
        return menuEntities;
    }


}
